<template>
	<view class="upload-goods">
		<u-form label-width="200" :model="goods" ref="goodsFrom">
			<div class="item-bg">
				<u-form-item required right-icon="arrow-right" label="商品类型">
					<u-input disabled v-model="categorySelected[1]" placeholder="请选择商品类型" @click="showCategroy" />
				</u-form-item>
			</div>
			<div class="item-bg">
				<u-form-item required label="商品名称" label-position="top" prop="goodsName">
					<u-input v-model="goods.goodsName" placeholder="请输入商品名称" />
				</u-form-item>
			</div>
			<div class="item-bg">
				<u-form-item required label-position="top" label="商品图片">
					<view class="image-flex-wrapper">
						<div class="image-wrapper" v-for="(item,index) in goods.goodsGalleryList" :key="index">
							<image @click="preview(item,goods.goodsGalleryList)" class="image" mode="aspectFill"
								:src="item"></image>
							<u-icon name="trash-fill" color="#f51818" class="del" size="30"
								@click="goods.goodsGalleryList.splice(index,1)"></u-icon>
						</div>
						<button type="default" @click="chooseImage('goodsGalleryList')" class="choose-image">+</button>
					</view>
				</u-form-item>
			</div>
			<div class="item-bg">
				<u-form-item required label="商品卖点" label-position="top" prop="sellingPoint">
					<u-input v-model="goods.sellingPoint" type="textarea" placeholder="请输入商品卖点" />
				</u-form-item>
			</div>
			<div class="item-bg">
				<u-form-item :border-bottom="false" label="商品品牌">
					<u-input v-model="goods.brandId" type="text" placeholder="请输入商品品牌" />
				</u-form-item>
			</div>
			<div class="item-bg">
				<u-form-item required right-icon="arrow-right" label="计量单位">
					<u-input disabled v-model="goods.goodsUnit" placeholder="请选择计量单位" @click="showUnit" />
				</u-form-item>
			</div>
			<div class="item-bg">
				<u-form-item label="销售模式">
					<div class="sale-type" v-if="goodsType === 'VIRTUAL_GOODS'">虚拟性</div>
					<div class="sale-type" v-if="goodsType === 'PHYSICAL_GOODS'">零售型</div>
				</u-form-item>
			</div>
			<div class="item-bg">
				<u-form-item label="销售区域">
					<div class="area-list">
						<div class="item" :class="{'active':goods.salesArea==='0'}" @click="chooseSaleArea('0')">
							全国销售
						</div>
						<div class="item" :class="{'active':goods.salesArea==='1'}" @click="chooseSaleArea('1')">
							{{area.region||'区域销售'}}
							<u-icon class="iconactive" name="arrow-right" size="24" color="#3640FF"></u-icon>
							<u-icon class="iconunactive" name="arrow-right" size="24" color="#ABABAB"></u-icon>
						</div>
					</div>
				</u-form-item>
			</div>

			<div class="item-bg" @click="toEditSpecs">
				<u-form-item required right-icon="arrow-right" label="商品规格">
					<u-input disabled v-model="specsText" placeholder="请添加商品规格" @click="toEditSpecs" />
				</u-form-item>
			</div>
			<div class="item-bg" @click="toEditGoodsDetail">
				<u-form-item required right-icon="arrow-right" label="图文详情">
					<u-input disabled v-model="goodsDetail" placeholder="请填写图文详情" @click="toEditGoodsDetail" />
				</u-form-item>
			</div>
			<div class="item-bg" @click="toStoreCateGory">
				<u-form-item right-icon="arrow-right" label="店铺分类">
					<u-input disabled v-model="storeCategoryText" placeholder="请选择店铺分类" @click="toStoreCateGory" />
				</u-form-item>
			</div>
			<div class="item-bg">
				<u-form-item required label="保质期" prop="shelfLife">
					<u-input v-model="goods.shelfLife" type="number" placeholder="请输入保质期(月)" />
				</u-form-item>
			</div>
			<div class="item-bg" @click="showDate" prop="productionDate">
				<u-form-item right-icon="arrow-right" required label="生产日期">
					<u-input disabled v-model="goods.productionDate" type="text" @click="showDate"
						placeholder="请选择生产日期" />
				</u-form-item>
			</div>
			<div class="item-bg" v-if="goodsType!=='VIRTUAL_GOODS'" @click="showShip">
				<u-form-item right-icon="arrow-right" required label="物流模板">
					<u-input disabled v-model="goods.templateName" type="text" @click="showShip"
						placeholder="请选择物流模板" />
				</u-form-item>
			</div>
			<div class="buttons-wrapper">
				<button class="button-add-prev" @click="uploadGoods(0)">放入仓库</button>
				<button class="button-add-save" @click="uploadGoods(1)">立即发布</button>
			</div>
		</u-form>
		<u-popup mode="center" :mask-close-able="false" border-radius="8" width="400" @close="goodsTypeClose"
			v-model="goodsTypeShow">
			<view class="choose-goodstype">
				<div class="item" @click="goodsTypeChoose('PHYSICAL_GOODS')">
					<div class="title">实物商品</div>
					<div class="subtitle">零售批发，物流配送</div>
				</div>
				<div class="item" @click="goodsTypeChoose('VIRTUAL_GOODS')">
					<div class="title">虚拟商品</div>
					<div class="subtitle">虚拟核验，无需物流</div>
				</div>
			</view>
		</u-popup>
		<u-select v-model="cateShow" mode="mutil-column-auto" :list="categoryList" @confirm="confirmCategory">
		</u-select>
		<u-select v-model="unitShow" mode="single-column" :list="goodsUnitList" @confirm="confirmUnit"></u-select>
		<u-select v-model="shipShow" mode="single-column" :list="shipTemplateList" @confirm="confirmShip"></u-select>
		<u-calendar v-model="dateShow" mode="date" @change="confirmDate"></u-calendar>
		<m-city topRight="confirm" :provinceData="[{id: '',localName: '请选择', children: [] }]" headTitle="区域选择"
			ref="cityPicker" @funcValue="getpickerParentValue" pickerSize="3">
		</m-city>
	</view>
</template>

<script>
	import api from "@/config/api.js";
	import storage from "@/utils/storage.js";
	import mCity from "@/components/m-city/m-city.vue";
	import {
		getCategoryList,
		goodsUnit,
		getShipTemplate,
		GetStoreCategory,
		UploadGoods
	} from "@/api/goods.js";
	export default {
		data() {
			return {
				goodsTypeShow: false, // 选择商品类型
				cateShow: false, // 分类
				unitShow: false, // 计量单位
				shipShow: false, // 物流模板
				dateShow: false, // 生产日期 
				showPicker: false, // 销售区域选择
				categorySelected: ['', ''],
				goodsType: "", // 商品类型：实物商品PHYSICAL_GOODS，虚拟商品VIRTUAL_GOODS
				areaList: ['全国销售', '区域销售'], // 销售区域列表
				area: {}, // 如果销售区域是地区销售，去定位选择区域
				goodsDetail: '', // 图文详情概要展示
				specsText: '', // 规格概要展示
				storeCategory: '', // 店铺分类列表
				storeCategoryText: '', // 店铺分类placeholder
				/** 发布商品基本参数 */
				goods: {
					origin: 'app', // 商品来源  移动端/pc端
					goodsName: '', // 商品名称
					goodsGalleryList: [], // 商品相册列表
					sellingPoint: "", //商品卖点
					brandId: '', // 商品品牌
					goodsUnit: '', // 计量单位
					salesModel: "RETAIL",
					salesArea: '0', // 销售区域
					intro: '', // 图文详情
					storeCategoryPath: '', // 店铺分类
					shelfLife: '', // 保质期
					productionDate: '', // 生产日期
					templateId: '0', // 物流模板ID
					templateName: '', // 物流模板名字
					updateSku: true, // 更新sku
					regeneratorSkuFlag: true, // 是否重新生成sku
				},
				goodsRules: {
					goodsName: [{
						required: true,
						message: "请输入商品名称",
						trigger: ["change", "blur"],
					}],
					sellingPoint: [{
						required: true,
						message: "请输入商品卖点",
						trigger: ["change", "blur"],
					}],
					shelfLife: [{
						required: true,
						message: "请输入保质期",
						trigger: ["change", "blur"],
					}]
				},
				categoryList: '',
				goodsUnitList: [],
				logisticsTemplateList: [],
				shipTemplateList: [], //物流模板列表
			}
		},
		components: {
			mCity
		},
		onReady() {
			this.$refs.goodsFrom.setRules(this.goodsRules);
		},
		onLoad() {
			// 先选择商品类型
			this.goodsTypeShow = true
			// 获取分类数据        
			this.initCategory()
			// 获取计量单位
			this.getGoodsUnit()
			// 获取电偶分类数据
			this.initStoreCategory()
		},
		onShow() {
			// 图文详情的缓存 如果有回显
			let goodsDetail = uni.getStorageSync('GoodsDetail')
			if (goodsDetail) {
				if (goodsDetail.content) {
					this.goodsDetail = goodsDetail.content
				} else if (goodsDetail.images && goodsDetail.images.length !== 0) {
					this.goodsDetail = '[图片]'
				} else {
					this.goodsDetail = ''
				}
			} else {
				this.goodsDetail = ''
			}
			// 店铺分类的缓存 如果有回显
			let StoreCategory = uni.getStorageSync('StoreCategory')
			if (StoreCategory) {
				let id = []
				let name = []
				for (let i = 0; i < StoreCategory.length; i++) {
					if (StoreCategory[i].check === true) {
						id.push(StoreCategory[i].id)
						name.push(StoreCategory[i].labelName)
					}
					for (let j = 0; j < StoreCategory[i].children.length; j++) {
						if (StoreCategory[i].children[j].check === true) {
							id.push(StoreCategory[i].children[j].id)
							name.push(StoreCategory[i].children[j].labelName)
						}
					}
				}
				this.goods.storeCategoryPath = id.join(',')
				this.storeCategoryText = name.join(' ')
			}
			// 规格的缓存 如果有回显
			let SpecsListOption = uni.getStorageSync('SpecsListOption')
			if (SpecsListOption) {
				let spec = SpecsListOption.map((item) => {
					return item.name
				})
				this.specsText = spec.join(' ')
			}
		},
		methods: {
			// 店铺分类 --start--
			showCategroy() {
				this.cateShow = true
			},
			confirmCategory(value) {
				console.log(value)
				let ids = []
				let names = []
				for (let i = 0; i < value.length; i++) {
					ids.push(value[i].value)
					names.push(value[i].label)
				}
				this.categorySelected = [ids.join(','), names.join(' ')]
			},
			// 店铺分类 --end--
			// 计量单位 --start--
			showUnit() {
				this.unitShow = true
			},
			confirmUnit(value) {
				this.goods.goodsUnit = value[0].label
			},
			// 计量单位 --end--
			// 物流模板 --start--
			showShip() {
				this.shipShow = true
			},
			confirmShip(value) {
				this.goods.templateId = value[0].value
				this.goods.templateName = value[0].label
			},
			// 物流模板 --end--
			// 生产日期 --start--
			showDate() {
				this.dateShow = true
			},
			confirmDate(value) {
				this.goods.productionDate = value.result
			},
			// 生产日期 --end--
			// 销售区域 选择
			chooseSaleArea(type) {
				this.goods.salesArea = type
				if (type === '1') {
					this.$refs.cityPicker.show();
				}
			},
			// 地区选择回调
			getpickerParentValue(e) {
				if (e.length !== 0) {
					let ids = e.map((item) => {
						return item.id
					})
					let last = e.pop()
					if (last.adCode) {
						this.area = {
							regionId: ids.join(','),
							region: last.localName
						}
					}
				}
			},
			// 去编辑图文详情
			toEditGoodsDetail() {
				uni.navigateTo({
					url: "/pages/business/upload-goods/edit-goods-detail"
				})
			},
			// 去编辑规格
			toEditSpecs() {
				uni.setStorageSync('GoodsAll', this.goods)
				uni.navigateTo({
					url: "/pages/business/upload-goods/edit-specs"
				})
			},
			// 去选择店铺分类
			toStoreCateGory() {
				if (this.storeCategory === '') {
					return
				}
				uni.setStorageSync('StoreCategory', this.storeCategory)
				uni.navigateTo({
					url: "/pages/business/upload-goods/store-category"
				})
			},
			// 获取商品分类
			async initCategory() {
				let list = await getCategoryList(0);
				let result = list.data.result;
				result = result.filter((item) => {
					return item.name === '实物商品'
				})
				let resultFormat = result.map((one) => {
					let oneChildren = one.children.map((two) => {
						if (two.children.length === 0) {
							return {
								value: two.id,
								label: two.name
							}
						} else {
							let twoChildren = two.children.map((three) => {
								return {
									value: three.id,
									label: three.name
								}
							})
							return {
								value: two.id,
								label: two.name,
								children: twoChildren
							}
						}
					})
					return {
						value: one.id,
						label: one.name,
						children: oneChildren
					}
				})
				console.log(resultFormat)
				this.categoryList = resultFormat
				console.log(this.categoryList)
			},
			// 商品类型弹窗关闭事件
			goodsTypeClose() {
				if (this.goodsType === '') {
					uni.navigateBack()
				}
			},
			// 选择商品类型
			goodsTypeChoose(type) {
				if (type === 'PHYSICAL_GOODS') {
					// 获取运费模板
					this.initGetShipTemplate()
				}
				this.goodsType = type
				this.goodsTypeShow = false
			},
			// 上传照片
			chooseImage(type, fileName) {
				let Token = storage.getAccessToken()
				let that = this
				uni.chooseImage({
					count: 9,
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: function(res) {
						var tempFilePaths = res.tempFilePaths
						for (let i = 0; i < tempFilePaths.length; i++) {
							uni.uploadFile({
								url: api.common + '/upload/file',
								fileType: "image",
								filePath: tempFilePaths[i],
								name: 'file',
								ruleForm: {},
								'content-type': 'multipart/form-data',
								header: {
									accessToken: Token,
									'content-type': 'multipart/form-data'
								}, // 设置请求的 header
								success: function(res) {
									res = JSON.parse(res.data)
									if (type == 'goodsGalleryList') {
										that.goods[type].push(res.result)
									} else {
										that.goods[type] = res.result
									}
								}
							})
						}

					}
				})
			},
			// 上传商品方法
			uploadGoods(type) {
				this.TYPE = type
				this.$refs.goodsFrom.validate((valid) => {
					if (valid) {
						let goods = JSON.parse(JSON.stringify(this.goods))
						goods.goodsType = this.goodsType
						// 发布 or 放入仓库   --start
						if (type === 1) {
							goods.release = true
							goods.recommend = false
						}
						if (type === 0) {
							goods.release = false
							goods.recommend = true
						}
						// 发布 or 放入仓库   --send
						// 商品类型  --start
						if (this.categorySelected[0]) {
							goods.categoryPath = this.categorySelected[0]
						} else {
							uni.showToast({
								title: '请选择商品类型',
								icon: "none"
							})
							return
						}
						// 商品类型  --send
						if (goods.goodsGalleryList.length === 0) {
							uni.showToast({
								title: '请上传商品图片',
								icon: "none"
							})
							return
						}
						// 规格项数据--start
						let SpecsListDetail = uni.getStorageSync('SpecsListDetail') // 规格详情
						let SpecsListOption = uni.getStorageSync('SpecsListOption') // 规格项
						let skuList = []
						for (let i = 0; i < SpecsListDetail.length; i++) {
							let obj = {}
							SpecsListDetail[i] = [...SpecsListDetail[i][0], ...SpecsListDetail[i][1]]
							for (let j = 0; j < SpecsListDetail[i].length; j++) {
								if (SpecsListDetail[i][j].slot === "images") {
									obj[SpecsListDetail[i][j].slot] = [{
										url: SpecsListDetail[i][j].value
									}]
								} else {
									obj[SpecsListDetail[i][j].slot] = SpecsListDetail[i][j].value
								}
							}
							skuList.push(obj)
						}
						if (skuList.length === 0) {
							uni.showToast({
								title: '请编辑规格',
								icon: "none"
							})
							return
						}
						goods.skuList = skuList
						console.log(skuList)
						// 规格项数据 --end
						// 图文详情  --start
						let goodsDetail = uni.getStorageSync('GoodsDetail')
						let intro = ''
						if (goodsDetail) {
							if (goodsDetail.content) {
								intro += `<p>${goodsDetail.content}</p>`
							}
							if (goodsDetail.images && goodsDetail.images.length !== 0) {
								for (let i = 0; i < goodsDetail.images.length; i++) {
									intro +=
										`<img src="${goodsDetail.images[i]}" contenteditable="false" style="font-size: 12px; max-width: 100%;"/>`
								}
							}
						}
						if (intro === '') {
							uni.showToast({
								title: '请填写图文详情',
								icon: "none"
							})
							return
						}
						goods.intro = intro
						// 图文详情  --end
						// 区域销售加定位 --start
						if (goods.salesArea === '1') {
							goods.regionId = this.area.regionId
							goods.region = this.area.region
						}
						// 区域销售加定位 --end
						if (!goods.productionDate) {
							uni.showToast({
								title: '请选择生产日期',
								icon: "none"
							})
							return
						}
						UploadGoods(goods).then((res) => {
							console.log(res)
							if (res.data.success) {
								if (type === 1) {
									uni.showToast({
										title: '商品发布成功，等待平台审核',
										icon: "none",
										duration: 3000
									})
								}
								if (type === 0) {
									uni.showToast({
										title: '商品已暂存仓库，可在商家平台端上架',
										icon: "none",
										duration: 3000
									})
								}
								uni.removeStorageSync('GoodsAll')
								uni.removeStorageSync('StoreCategory')
								uni.removeStorageSync('GoodsDetail')
								uni.removeStorageSync('SpecsListDetail')
								uni.removeStorageSync('SpecsListOption')
								setTimeout(() => {
									uni.navigateBack()
								}, 3000)
							}
						})
						console.log(JSON.stringify(goods))
					}
				})
			},
			// 获取商品单位
			getGoodsUnit() {
				goodsUnit().then((res) => {
					res = res.data
					if (res.success) {
						this.goodsUnitList = res.result.records.map((i) => {
							return {
								value: i.name,
								label: i.name
							}
						});
						this.goods.goodsUnit = this.goodsUnitList[0].label
					}
				});
			},
			// 获取运费模板
			initGetShipTemplate() {
				getShipTemplate().then((res) => {
					res = res.data
					if (res.success) {
						if (res.result.length === 0) {
							uni.showToast({
								title: '请先在商家后台设置物流模板',
								icon: "none",
								duration: 5000
							})
							setTimeout(() => {
								uni.navigateBack()
							}, 3000)
							return
						}
						this.shipTemplateList = res.result.map((i) => {
							return {
								value: i.id,
								label: i.name
							}
						});
						this.goods.templateId = this.shipTemplateList[0].value
						this.goods.templateName = this.shipTemplateList[0].label
					} else {
						uni.showToast({
							title: '请先在商家后台设置物流模板',
							icon: "none",
							duration: 5000
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 3000)
						return
					}
				})
			},
			// 获取店铺分类数据
			initStoreCategory() {
				GetStoreCategory().then((res) => {
					console.log(res)
					if (res.data.success) {
						let result = res.data.result
						if (result.length === 0) {
							this.storeCategory = ''
							this.storeCategoryText = '暂无店铺分类'
						} else {
							for (let i = 0; i < result.length; i++) {
								result[i].check = false
								for (let j = 0; j < result[i].children.length; j++) {
									result[i].children[j].check = false
								}
							}
							this.storeCategory = result
						}
					} else {
						this.storeCategory = ''
						this.storeCategoryText = '暂无店铺分类'
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	.upload-goods {
		padding: 16upx 0 40upx 0;

		.item-bg {
			padding: 0 40upx;
			background-color: #ffffff;
			margin-bottom: 16upx;
		}

		.area-list {
			display: flex;
			overflow: hidden;


			.item {
				margin-right: 24upx;
				flex: 0 0 160upx;
				width: 160upx;
				height: 56upx;
				line-height: 56upx;
				box-sizing: content-box;
				border-radius: 12upx;
				text-align: center;
				color: #ABABAB;
				border: 2upx solid #e3e3e3;
				display: flex;
				align-items: center;
				justify-content: space-around;
				font-size: 24upx;

				.iconactive {
					display: none;
				}

				.iconunactive {
					display: block;
				}
			}

			.active {
				border: 2upx solid #3640FF;
				color: #3640FF;

				.iconactive {
					display: block;
				}

				.iconunactive {
					display: none;
				}
			}
		}

		.sale-type {
			border: 2upx solid rgba(255, 204, 184, 1);
			width: 120upx;
			height: 56upx;
			line-height: 56upx;
			text-align: center;
			font-size: 24upx;
			color: rgba(255, 133, 133, 1);
			box-sizing: content-box;
			border-radius: 12upx;
		}

		.image-flex-wrapper {
			display: flex;
			flex: 0 0 140upx;
			flex-direction: row;
			flex-wrap: wrap;

			.image-wrapper {
				position: relative;

				.del {
					position: absolute;
					top: 24upx;
					right: 24upx;
				}
			}

			.image {
				margin: 12upx;
				width: 140upx;
				height: 140upx;
				vertical-align: middle;

			}

			.choose-image {
				margin: 12upx;
				width: 140upx;
				height: 140upx;
				line-height: 140upx;
				font-size: 40px;
				border: 1px dashed #999;
			}
		}

		.choose-goodstype {
			padding: 24upx;

			.item {
				margin: 24upx;

				.title {
					font-size: 32upx;
					font-weight: bold;
				}

				.subtitle {
					margin-top: 12upx;
					font-size: 28upx;
					color: #999999;
				}
			}
		}

		.buttons-wrapper {
			display: flex;
			justify-content: space-around;
			padding: 32upx;

			.button-add-prev {
				width: 280upx;
				height: 80upx;
				line-height: 80upx;
				border-radius: 40upx;
				color: rgba(18, 125, 255, 1);
				font-size: 28upx;
				border: 2upx solid rgba(18, 125, 255, 1);
			}

			.button-add-save {
				width: 260upx;
				height: 80upx;
				line-height: 80upx;
				background: linear-gradient(270deg, rgba(118, 194, 245, 1) 0%, rgba(18, 125, 255, 1) 100%);
				border-radius: 40upx;
				color: #ffffff;
				font-size: 28upx;
			}
		}
	}
</style>
